%%% -------------------------------------------------------------------
%%% Author  : zyb
%%% Description :
%%% genserver . ifriend . 
%%% Created : 2009-7-8
%%% -------------------------------------------------------------------
-module(ifriend_server).
-behaviour(gen_server).
-include("../include/header.hrl").
%% --------------------------------------------------------------------
%% Include files
%% --------------------------------------------------------------------

%% --------------------------------------------------------------------
%% External exports
-export([start/0,stop/0]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
-complie(export_all).


start() ->
	io:format("ifriend server is starting!~n"),
    ifriend_db:start_mnesia(),
	error_logger:error_msg("!!!!!!!~n"),	
    gen_server:start_link({global,?SERVER_NAME},?MODULE,[],[]).

stop() ->
    gen_server:cast(?SERVER_NAME, stop).


%% ====================================================================
%% Server functions
%% ====================================================================

%% --------------------------------------------------------------------
%% Function: init/1
%% Description: Initiates the server
%% Returns: {ok, State}          |
%%          {ok, State, Timeout} |
%%          ignore               |
%%          {stop, Reason}
%% --------------------------------------------------------------------
init([]) ->
    process_flag(trap_exit, true),
    {ok,[]}.

%% --------------------------------------------------------------------
%% Function: handle_call/3
%% Description: Handling call messages
%% Returns: {reply, Reply, State}          |
%%          {reply, Reply, State, Timeout} |
%%          {noreply, State}               |
%%          {noreply, State, Timeout}      |
%%          {stop, Reason, Reply, State}   | (terminate/2 is called)
%%          {stop, Reason, State}            (terminate/2 is called)
%% --------------------------------------------------------------------
%%ifriend 实现的 operation 接口
%%	meta 负责登录 
%%======================================================= Interface

%%	login:  1 . check id  2 . check session 3 . get worker process name by ID+Session 4 return pname 
handle_call({login,ID,Session},_From,State)->
	chekid,
	checkSession,
	Reply = util:generate_workername(ID,Session),
	{reply,Reply,State};

handle_call({sync_contacts,_ID,_Session},_From,State)->
	Reply = r,
	{reply,Reply,State};

%%========================================================Functions 
%%	query friends of my storage  
handle_call(
  			{queryAllFollowed,ID,Session},
			From,State) ->
	case checkSession2(ID,Session) of
		ok->
			WorkerName = integer_to_list(ID),
			case whereis(WorkerName) of
				undefined->
					{ok, WorkerPid}=gen_server:start({local,WorkerName}, ifriend_worker, [ID], []),
					Reply = gen_server:call(WorkerPid,{queryAllfollowd}),
					error_logger:error_msg("reply of call queryallfollowd: ~p~n",[Reply]),
					{reply,Reply,State};
					
				WorkerPID->
					Reply = gen_server:call(WorkerPID,{queryAllfollowd}),
					error_logger:error_msg("reply of call queryallfollowd: ~p~n",[Reply]),
					{reply,Reply,State}
	
			end;
		{error,Why}->
			error		
	end;

%%	query my Frame.of.mind state 
handle_call(
  			{queryFrame,ID},
			From,State) ->
	Reply = ifriend_common:queryFrameFunc(ID),
	error_logger:error_msg("From: ~p~n",[From]),
	error_logger:error_msg("reply of call queryFrame: ~p~n",[Reply]),
	{reply,Reply,State};

handle_call(
  			{newfom,ID,NEW},
			From,State)->
	Reply = ifriend_common:newfomFunc(ID,NEW),
	{reply,Reply,State};





handle_call(_Request, _From, State) ->
    Reply = ok,
    {reply, Reply, State}.





%% --------------------------------------------------------------------
%% Function: handle_cast/2
%% Description: Handling cast messages
%% Returns: {noreply, State}          |
%%          {noreply, State, Timeout} |
%%          {stop, Reason, State}            (terminate/2 is called)
%% --------------------------------------------------------------------
handle_cast(_Msg, State) ->
    {noreply, State}.

%% --------------------------------------------------------------------
%% Function: handle_info/2
%% Description: Handling all non call/cast messages
%% Returns: {noreply, State}          |
%%          {noreply, State, Timeout} |
%%          {stop, Reason, State}            (terminate/2 is called)
%% --------------------------------------------------------------------
handle_info(_Info, State) ->
    {noreply, State}.

%% --------------------------------------------------------------------
%% Function: terminate/2
%% Description: Shutdown the server
%% Returns: any (ignored by gen_server)
%% --------------------------------------------------------------------
terminate(Reason, _State) ->
      io:format("ifriend server terminating.abc. reason:~n"),
	  io:format("~p~n",[Reason]),
	  ok.

%% --------------------------------------------------------------------
%% Func: code_change/3
%% Purpose: Convert process state when code is changed
%% Returns: {ok, NewState}
%% --------------------------------------------------------------------
code_change(_OldVsn, State, _Extra) ->
    {ok, State}.

%% --------------------------------------------------------------------
%%% Internal functions
%% --------------------------------------------------------------------

checkSession2(ID,Session)->
	ok.

%% @spec checkSession(ID,Session) -> ok | {error,Why} 
checkSession(ID,Session)->
	case ifriend_db:select_from_login_byid(ID) of		
		[]->
			error_logger:error_msg("no user id"),
			{error,"no_user"};
		[Login]->
			Sec = Login#login.session,
			if 				
				Sec =/= Session ->
					error_logger:error_msg(" wrong session "),
					{error,"wrong session"};
				true->
					ok			
			end
	end.
				   
		
			
													  
	
	
	
	
